package org.hxzon.tapestry5.pages;

import java.io.File;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.tapestry5.util.FileStreamResponse;
import org.slf4j.Logger;

public class StaticFileResponse {
    @Inject
    private Logger logger;
    @Inject
    private ServletContext servletContext;

    @OnEvent(value = EventConstants.ACTIVATE)
    protected Object response(String path) {
        InputStream targetFile = null;
        try {
            targetFile = FileUtils.openInputStream(new File(servletContext.getRealPath(path)));
        } catch (Exception e) {
            logger.error("文件不存在:{}", e.getMessage());
        }
        if (targetFile == null) {
            targetFile = IOUtils.toInputStream("");
        }
        return new FileStreamResponse(targetFile, "", true);
    }
}
